import React, { useEffect } from 'react';

function ajax(url) {
  return new Promise(function (resolve, reject) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.responseType = 'json';
    xhr.onload = function () {
      switch (this.status) {
        case 200:
          resolve(this.response);
          break;
        case 404:
          reject(new Error('找不到的异常'));
          break;
        default:
          reject(new Error(this.statusText));
          break;
      }
    };
    xhr.send();
  });
}

async function main() {
  const { data: user } = await ajax('http://localhost:3001/api/userData');
  console.log(user);

  const { data: post } = await ajax('http://localhost:3001/api/postData');
  console.log(post);

  const err = await ajax('/api/errData');
  console.log(err);
}

export default function Increase() {
  useEffect(() => {
    main(); // 调用时省略了 co 函数
  }, []);

  return (
    <div>
      <p>Promise 的 async await 用法</p>
    </div>
  );
}
